import React, {useCallback, useEffect, useMemo, useState} from "react"
import {Pageable} from "../../utils/Page";
import {createMarket, queryMarkets, QueryMarketsResponse, updateMarket} from "../../apis/MarketsApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {Button, ConfigProvider, Form, Input, Select, Table, Transfer, Typography} from "antd";
import {EditOutlined, PlusOutlined} from "@ant-design/icons";
import {castFilterValue, mergePaginationAndPageable, useTableSearchTextColumnProps} from "../../utils/AntdTableUtils";
import {QueryGoodsResponse} from "../../apis/GoodsApi";
import DataPageLayout from "../../components/DataPageLayout";
import FormDrawer from "../../components/FormDrawer";
import {Link} from "react-router-dom";
import {NumberIdAndName} from "../../types/BasicModels";
import {getAllEmployeeSummariesSortBySaleManager} from "../../apis/EmployeeApi";
import {createMarketOrder} from "../../apis/MarketOrderApi";
import {useNavigate} from "react-router";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {getAllGoodsBrand, GoodsBrandSummary} from "../../apis/GoodsBrandsApi";
import {useGlobalStyle} from "../../global.style";
import AdministrativeRegionCascader from "../AdministrativeRegionCascader";
import MapAddressSelector, {MapAddressSelectorValue} from "../MapAddressSelector";

export interface pageProps {

}

export interface MarketFormData {
    name: string
    saleManagerId?: number
    excludeBrandIds: number[]
    shoppingGuideIds: number[]
    address?: MapAddressSelectorValue
}


const MarketPage: React.FC<pageProps> = () => {
    const [openAddDrawer, setOpenAddDrawer] = useState(false)
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketsResponse[]>([])
    const [searchNameText, setSearchNameText] = useState<string>()
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)


    const [editingItemId, setEditingItemId] = useState<number>()
    const editingItem = useMemo(() => {
        return data.find(it => it.id === editingItemId)
    }, [editingItemId, data]);

    let query = useCallback(() => {
        setLoading(true)
        queryMarkets({name: searchNameText,}, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), searchNameText,]);

    useEffect(() => {
        query()
    }, [query]);
    let nameSearchProps = useTableSearchTextColumnProps<QueryGoodsResponse>("name", {
        placeholder: "名称"
    });

    const [employees, setEmployees] = useState<NumberIdAndName[]>([])
    const [searchSaleManagerText, setSearchSaleManagerText] = useState("")
    useEffect(() => {
        getAllEmployeeSummariesSortBySaleManager().then(response => {
            setEmployees(response.data)
        })
    }, []);
    const searchedEmployees = useMemo(() => {
        return employees.filter(it => it.name.includes(searchSaleManagerText))
    }, [searchSaleManagerText, employees]);
    const [searchShoppingGuideText, setSearchShoppingGuideText] = useState("")
    const searchedShoppingGuides = useMemo(() => {
        return employees.filter(it => it.name.includes(searchShoppingGuideText))
    }, [searchShoppingGuideText, employees]);
    let navigate = useNavigate();

    const [brands, setBrands] = useState<GoodsBrandSummary[]>([]);
    useEffect(() => {
        getAllGoodsBrand().then(value => setBrands(value.data))
    }, []);
    const [selectedBrandIds, setSelectedBrandIds] = useState<number[]>([])
    useEffect(() => {
        setSelectedBrandIds(editingItem?.excludeBrands?.map(it => it.id) ?? [])
    }, [editingItem]);

    function buildFormItems() {
        return <>
            <Form.Item label={"名称"} name="name" rules={[{required: true}]}>
                <Input/>
            </Form.Item>
            <Form.Item label={"业务员"} name="saleManagerId">
                <Select placeholder={"选择业务员"} showSearch onSearch={value => {
                    setSearchSaleManagerText(value)
                }}>
                    {searchedEmployees.map(employee => <Select.Option value={employee.id}
                                                                      key={employee.id}>{employee.name}</Select.Option>)}
                </Select>
            </Form.Item>
            <Form.Item label={"导购"} name="shoppingGuideIds">
                <Select mode={"multiple"} placeholder={"选择导购"} showSearch onSearch={value => {
                    setSearchShoppingGuideText(value)
                }}>
                    {searchedShoppingGuides.map(employee => <Select.Option value={employee.id}
                                                                           key={employee.id}>{employee.name}</Select.Option>)}
                </Select>
            </Form.Item>
            <Form.Item label={"排除品牌"} name="excludeBrandIds">
                <Transfer<NumberIdAndName> dataSource={brands.map(brand => ({...brand, key: brand.id.toString()}))}
                                           titles={["可选", "已选"]}
                                           onChange={targetKeys => {
                                               setSelectedBrandIds(targetKeys.map((it ) => parseInt(it as unknown as string)))
                                           }}
                                           targetKeys={selectedBrandIds?.map(it => it.toString()) ?? []}
                                           render={item => item.name}
                />
            </Form.Item>
            <Form.Item label={"地址"} name={"address"}>
                <MapAddressSelector/>
            </Form.Item>
        </>
    }

    let globalStyle = useGlobalStyle();

    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["卖场_新增"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>新增卖场</Button>
        </AuthorizationResource>}>
            <ConfigProvider componentSize={"small"}>
                <Table className={globalStyle.rowClickableTable} onRow={item=>({
                    onClick: (record) => {
                        navigate(`/markets/${item.id}`)
                    }
                })} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                    current: pageable.page,
                    pageSize: pageable.size,
                    total: totalElements,
                }} onChange={(pagination, filters, sorter) => {
                    setSearchNameText(castFilterValue(filters.name))
                    setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                }}>
                    <Table.Column dataIndex={"name"} title={"名称"} {...nameSearchProps} />
                    <Table.Column dataIndex={["saleManager", "name"]} title={"业务员"}/>
                    <Table.Column<QueryMarketsResponse> dataIndex={["administrativeRegion"]} title={"区划"} render={(_, record, index)=>{
                        return <Typography.Text>
                            {[record.province,record.city,record.district].filter(Boolean).map(it=>it!.name).map((name,index)=>{
                                return <>
                                    {index!==0?<Typography.Text type={"secondary"}>/</Typography.Text>:undefined}
                                    <Typography.Text>{name}</Typography.Text>
                                </>
                            })}
                        </Typography.Text>
                    }}/>
                    <Table.Column dataIndex={"goodsAmount"} title={"单品数量"}/>
                    <Table.Column<QueryMarketsResponse> title={"操作"} render={(_, item) => {
                        return <>
                            <AuthorizationResource authorities={[]}>
                                <Link to={`/markets/orders?marketIds=${item.id}`} >
                                    <Button type={"link"}>订货单</Button>
                                </Link>
                            </AuthorizationResource>
                            <AuthorizationResource authorities={[]}>
                                <Button type={"link"} onClick={event => {
                                    event.stopPropagation()
                                    createMarketOrder(item.id).then(response => {
                                        navigate(`/markets/orders/${response.data}`)
                                    })
                                }}>下单</Button>
                            </AuthorizationResource>
                            <AuthorizationResource authorities={["卖场_修改"]}><Button type={"link"}
                                                                                           onClick={event => {
                                                                                               event.stopPropagation()
                                                                                               setEditingItemId(item.id)
                                                                                           }}>
                                <EditOutlined/>
                                修改
                            </Button>
                            </AuthorizationResource>
                        </>
                    }}/>
                </Table>
            </ConfigProvider>
        </DataPageLayout>
        <FormDrawer<MarketFormData> onClose={() => setOpenAddDrawer(false)}
                                    title={"新增卖场"}
                                    onConfirm={async (values) => {
                                        return createMarket({...values, excludeBrandIds: selectedBrandIds,...values.address,address:values.address?.address,districtCode:values.address?.adcode,}).then(() => {
                                            setOpenAddDrawer(false)
                                            query()
                                        })
                                    }}
                                    open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
        <FormDrawer<MarketFormData> open={!!editingItem} title={"修改卖场"} onClose={() => {
            setEditingItemId(undefined)
        }} onConfirm={async (values) => {
            return updateMarket(editingItemId!!, {...values, excludeBrandIds: selectedBrandIds,...values.address,address:values.address?.address,districtCode:values.address?.adcode,}).then(() => {
                query()
                setEditingItemId(undefined)
            })
        }} initialValues={editingItem ? {
            name: editingItem.name ?? "",
            saleManagerId: editingItem.saleManager?.id,
            excludeBrandIds: editingItem.excludeBrands.map(it => it.id),
            shoppingGuideIds: editingItem.shoppingGuides?.map(it => it.id),
            address: editingItem?.address? {
                longitude:editingItem.longitude!!,
                latitude:editingItem.latitude!!,
                address:editingItem.address!!,
                addressName:editingItem.addressName!!,
                adcode:editingItem.district!!.code,
            }:undefined
        } : undefined}>
            {buildFormItems()}
        </FormDrawer>
    </>
}


export default observerDashboardPageWrapper(MarketPage, "markets", "卖场")
